﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Threading;
using NetBay.Core.Log;

#endregion

namespace Rio.Workflow.Runtime
{
    public class WorkerQueue
    {
        #region Constructors

        /// <summary>
        /// Workers the queue.
        /// </summary>
        public WorkerQueue()
        {
            ThreadPool.SetMaxThreads(1, 1);
        }

        #endregion

        #region Instance Methods

        /// <summary>
        /// Adds the job.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="executor">The executor.</param>
        /// <param name="request">The request.</param>
        public void AddAction(WorkflowContextBase item, IActionExecutor executor, ActionRequest request)
        {
            ThreadPool.QueueUserWorkItem(PerformWork_Internal, new object[] {item, executor, request});
        }

        /// <summary>
        /// Performs the work_ internal.
        /// </summary>
        /// <param name="state">The state.</param>
        private void PerformWork_Internal(object state)
        {
            try
            {
                object[] array = state as object[];
                if (array != null)
                {
                    WorkflowContextBase instance = (WorkflowContextBase) array[0];

                    instance.RaiseBeforeExecuteAction();
                    ((WorkflowContextBase) array[0]).ExecuteAction(array[1] as IActionExecutor,
                                                                   array[2] as ActionRequest);
                    instance.RaiseAfterExecuteAction();
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError("Unable to execute the action: " + ex.Message);
            }
        }

        #endregion
    }
}